﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Microsoft.Office.OneNote
{
    [OneNoteXmlElement("T")]
    public sealed class OneNoteTextRange : OneNoteObject, IEquatable<OneNoteTextRange>, IOneNoteSchemaCallback
    {
        private string _value;

        public OneNoteTextRange()
        {
        }

        public OneNoteTextRange(string text)
        {
            _value = text;
        }

        public override int GetHashCode()
        {
            return (_value ?? string.Empty).GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return this.EqualsHelper(obj);
        }

        public bool Equals(OneNoteTextRange other)
        {
            if (ReferenceEquals(other, null))
            {
                return false;
            }

            if (string.IsNullOrEmpty(_value))
            {
                return string.IsNullOrEmpty(other._value);
            }

            return _value.Equals(other._value);
        }

        public override string ToString()
        {
            return _value ?? string.Empty;
        }

        void IOneNoteSchemaCallback.Deserialize(XElement element)
        {
            StringBuilder str = new StringBuilder();

            foreach (XCData cdata in element.Nodes().OfType<XCData>())
            {
                str.Append(cdata.Value);
            }

            _value = str.ToString();
        }

        void IOneNoteSchemaCallback.Serialize(XElement element)
        {
            element.Add(new XCData(_value));
        }
    }
}
